package com.study.rabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@SuppressWarnings("all")
public class RabbitConfig {
    //分别声明交换机名称和队列名称
    public static final String EXCHANGE_NAME = "normal_exchange";
    public static final String QUEUE_NAME = "normal_queue";
    //分别声明死信交换机和队列名称
    public static final String DLX_EXCHANGE_NAME = "dlx_exchage";
    public static final String DLX_QUEUE_NAME = "dlx_queue";

    //创建死信交换机
    @Bean("dlxExchage")
    public Exchange dlxExchage() {
        return ExchangeBuilder.topicExchange(DLX_EXCHANGE_NAME).durable(true).build();
    }
    //创建死信队列
    @Bean("dlxQueue")
    public Queue dlxQueue() {
        return QueueBuilder.durable(DLX_QUEUE_NAME).build();
    }
    //将死信交换机和死信队列绑定
    @Bean
    public Binding bindingDlx(@Qualifier("dlxExchage") Exchange exchange, @Qualifier("dlxQueue") Queue queue) {
        return BindingBuilder.bind(queue).to(exchange).with("dlx.*").noargs();
    }

    //依次配置交换机、队列、绑定器对应的Bean
    @Bean("normalExchange")
    public Exchange exchange() {
        return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
    }
    @Bean("normalQueue")
    public Queue queue() {
        return QueueBuilder
                .durable(QUEUE_NAME) //创建持久化队列
                .expires(24 * 60 * 60 * 1000) //设置队列的超时销毁时间，如果队列在连续的50000ms都没有存储消息，该队列将被delete，保证资源及时回收
                .ttl(30 * 60 * 1000) //设置消息的超时时间，如果消息在存储后1000ms都没有被消费则会被删除或写入死信队列（如果设置了死信队列）
                .deadLetterExchange(DLX_EXCHANGE_NAME) //超时的消息不会被直接删除，而是写入死信队列
                .deadLetterRoutingKey("dlx.info")//声明死信消息的 routingKey
                .build();
    }
    @Bean
    public Binding binding(@Qualifier("normalExchange") Exchange exchange,
                           @Qualifier("normalQueue") Queue queue) {
        // channel.queueBind(queue1, exchange, "libai.*");//只要是李白的诗都保存到队列1
        return BindingBuilder.bind(queue).to(exchange).with("*.info").noargs();
    }
}
